
package com.phantom;

import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.util.ArrayList;
import java.util.List;

/**
 * @Classname TestphanhtomReference
 * @Description 虚引用
 * @Date 2022/4/14 14:53
 * @Created by 86182
 */
public class TestphanhtomReference {
    public static void main(String[] args) {
        ReferenceQueue<String> queue = new ReferenceQueue<>();
        List<MyResoure> list = new ArrayList<>();
        list.add(new MyResoure(new String("a"), queue));
        list.add(new MyResoure(new String("b"), queue));
        list.add(new MyResoure(new String("c"), queue));
        System.gc();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Reference<? extends String> poll = queue.poll();
        while (poll != null) {
            System.out.println("celan");
        }

    }


    static class MyResoure extends PhantomReference<String> {

        /**
         * Creates a new phantom reference that refers to the given object and
         * is registered with the given queue.
         *
         * <p> It is possible to create a phantom reference with a <tt>null</tt>
         * queue, but such a reference is completely useless: Its <tt>get</tt>
         * method will always return null and, since it does not have a queue, it
         * will never be enqueued.
         *
         * @param referent the object the new phantom reference will refer to
         * @param q        the queue with which the reference is to be registered,
         */
        public MyResoure(String referent, ReferenceQueue<? super String> q) {
            super(referent, q);
        }

        // 释放外部资源方法
        public void clean() {
            System.out.println("clean");
        }
    }
}
